package org.example.observe.service.impl;

import lombok.extern.slf4j.Slf4j;
import org.example.observe.service.OrderEvent;
import org.example.observe.service.OrderObserve;
import org.example.observe.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationEvent;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.Observable;

@Slf4j
@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    private ApplicationContext applicationContext;

    /**
     * 订单支付成功:没有业务间独立没有顺序
     * 1.修改支付单为成功
     * 2.需要进行发货
     * 3.给用户新增积分
     * 4.统计。。。
     *
     * @param orderNo
     * @return
     */
    @Override
    public String paySuccess(String orderNo) {
        // 订单状态变更属于该业务处理
        log.info("1.修改支付单为成功");

        // 自定义方式
        notifyByOrderObserve(orderNo);

        // Spring方式
//        notifyBySpring(orderNo);

        // JDK方式,Observable,Observer
        return "ok";
    }

    private void notifyBySpring(String orderNo) {
        // 发布事件
        applicationContext.publishEvent(new OrderEvent(orderNo));
    }

    private void notifyByOrderObserve(String orderNo) {
        // 通知剩余业务
        Map<String, OrderObserve> observeMap = applicationContext.getBeansOfType(OrderObserve.class);
        for (OrderObserve observe : observeMap.values()) {
            observe.paySuccess(orderNo);
        }
    }
}
